package com.link.play.fit.ai.ui.main.saveFood.details

import android.Manifest
import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import com.bumptech.glide.Glide
import com.google.gson.Gson
import com.link.play.fit.ai.R
import com.link.play.fit.ai.base.BaseActivity
import com.link.play.fit.ai.base.goToAc
import com.link.play.fit.ai.base.goToAcForResult
import com.link.play.fit.ai.bean.CalendarStatusData
import com.link.play.fit.ai.bean.CollectFoodInfoData
import com.link.play.fit.ai.bean.InfoIngredientsBean
import com.link.play.fit.ai.bean.ServingTypeBean
import com.link.play.fit.ai.bean.toInfoIngredients
import com.link.play.fit.ai.bean.updateFoodInfoBean
import com.link.play.fit.ai.databinding.FoodDetailLayoutBinding
import com.link.play.fit.ai.ext.checkPermissions
import com.link.play.fit.ai.ext.d
import com.link.play.fit.ai.ext.setThrottleListener
import com.link.play.fit.ai.store.CloudStore
import com.link.play.fit.ai.store.CloudStore.DOC_SAVE_FOOD_COLLECT_DATA
import com.link.play.fit.ai.store.CloudStore.deleteList
import com.link.play.fit.ai.ui.main.saveFood.details.modifyPage.ModifyCaloriesAc
import com.link.play.fit.ai.ui.main.saveFood.details.modifyPage.ModifyCarbsAc
import com.link.play.fit.ai.ui.main.saveFood.details.modifyPage.ModifyFatsAc
import com.link.play.fit.ai.ui.main.saveFood.details.modifyPage.ModifyProteinAc
import com.link.play.fit.ai.utils.BitmapUtils.getScreenBitmap
import com.link.play.fit.ai.utils.BitmapUtils.saveBitmapToFile
import com.link.play.fit.ai.utils.DateEx.getPmDate
import com.link.play.fit.ai.utils.ShareFileUtils.getImageMediaId
import com.link.play.fit.ai.utils.ShareFileUtils.shareFile
import com.link.play.fit.ai.utils.ShareFileUtils.shareMedia
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.io.File
import kotlin.math.abs
import kotlin.math.floor
import kotlin.math.roundToInt


class FoodDtailsAc : BaseActivity<FoodDetailLayoutBinding>(FoodDetailLayoutBinding::inflate) {

    companion object {
        const val Type1 = 1 //按照份数计算
        const val Type2 = 2 //按照克数计算
    }

    private val EPSILON: Double = 0.0001 // 用于浮点数精度比较
    private var mName = ""

    private var currentValue = 1.0
    private var calendarStatusData: CalendarStatusData? = null
    private var collectFoodInfoData: CollectFoodInfoData? = null

    private var foodType = 0 //1是按照份数计算  2 是按照克数计算
    private var ingredients: InfoIngredientsBean? = null
    private var serving: ServingTypeBean? = null
    private var percent: Double = 1.0  // 按照克数计算时的比率

    override fun useDefaultImmersive() {
        ViewCompat.setOnApplyWindowInsetsListener(binding.root) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, 0, systemBars.right, systemBars.bottom)
            insets
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initData()
        initListener()
        EventBus.getDefault().register(this)
    }

    private fun initData() {
        calendarStatusData = intent.getSerializableExtra("bean") as CalendarStatusData?
        collectFoodInfoData = intent.getSerializableExtra("foodBean") as CollectFoodInfoData?
        "collectFoodInfoData  $collectFoodInfoData".d()

        if (!TextUtils.isEmpty(collectFoodInfoData?.ingredients)) {
            ingredients = Gson().fromJson(
                collectFoodInfoData?.ingredients,
                InfoIngredientsBean::class.java
            )
            serving = ingredients?.servingTypes?.find {
                if (it.id == ingredients?.servingTypeId) {
                    return@find true
                } else {
                    return@find false
                }
            }
            if (serving?.metricUnit == "g" || serving?.metricUnit == "G") {

                foodType = 2
                currentValue =
                    (collectFoodInfoData?.servings ?: 1.0) * (serving?.metricAmount?.toDouble()
                        ?: 1.0)
            } else {
                foodType = 1
                currentValue = collectFoodInfoData?.servings ?: 1.0
            }
        } else {
            foodType = 1
            currentValue = collectFoodInfoData?.servings ?: 1.0
        }
        collectFoodInfoData?.let {
            binding.dateText.text = getPmDate(it.timeMillisecond)
            binding.foodNameText.text = it.name
            Glide.with(this)
                .load(it.img)
                .error(R.mipmap.icon_canju) // 加载失败时显示的图片
                .fallback(R.mipmap.icon_canju)
                .into(binding.canjuImg)
        }
        if (TextUtils.isEmpty(collectFoodInfoData?.img)) {

        } else {
            //如果有图片
            binding.canjuImg.visibility = View.INVISIBLE
            Glide.with(this).load(collectFoodInfoData?.img)
                .override(
                    com.bumptech.glide.request.target.Target.SIZE_ORIGINAL,
                    resources.getDimensionPixelSize(R.dimen.dp_350)
                ) // maxHeight 为最大高度
                .into(binding.ivFood)
        }
        updateDisplay()
    }

    private fun initListener() {
        with(binding) {
            backImage.setOnClickListener {
                finish()
            }
            foodNameText.setThrottleListener {
                lifecycleScope.launch {
                    val result = goToAcForResult(ModifyFoodNameAc::class.java) {
                        putExtra("name", foodNameText.text.toString())
                    }
                    when (result.resultCode) {
                        RESULT_OK -> {
                            val data = result.data?.getStringExtra("result_key").toString()
                            mName = data
                            foodNameText.text = data
                            collectFoodInfoData?.apply {
                                name = data
                            }

                        }
                    }
                }
            }

            calorieLayout.setThrottleListener {
                lifecycleScope.launch {
                    val result = goToAcForResult(ModifyCaloriesAc::class.java) {
                        putExtra("value", caloriesValueText.text.toString())
                        putExtra("bean", calendarStatusData)
                    }
                    when (result.resultCode) {
                        RESULT_OK -> {
                            val cal = result.data?.getStringExtra("result_key")
                            caloriesValueText.text = cal
                            collectFoodInfoData?.apply {
                                cal?.let {
                                    calories = it.toDouble()
                                }
                            }
                        }
                    }
                }
            }
            carbsLayout.setThrottleListener {
                lifecycleScope.launch {
                    val result = goToAcForResult(ModifyCarbsAc::class.java) {
                        putExtra("value", carbsValueText.text.toString())
                        putExtra("bean", calendarStatusData)

                    }
                    when (result.resultCode) {
                        RESULT_OK -> {
                            val value = result.data?.getStringExtra("result_key").toString()
                            carbsValueText.text = value
                            collectFoodInfoData?.apply {
                                carbs = value.toDouble()
                            }
                        }
                    }
                }
            }
            proteinLayout.setThrottleListener {
                lifecycleScope.launch {
                    val result = goToAcForResult(ModifyProteinAc::class.java) {
                        putExtra("value", proteinValueText.text.toString())
                        putExtra("bean", calendarStatusData)

                    }
                    when (result.resultCode) {
                        RESULT_OK -> {
                            val value = result.data?.getStringExtra("result_key").toString()
                            proteinValueText.text = value
                            collectFoodInfoData?.apply {
                                protein = value.toDouble()
                            }
                        }
                    }
                }

            }
            fatsLayout.setThrottleListener {
                lifecycleScope.launch {
                    val result = goToAcForResult(ModifyFatsAc::class.java) {
                        putExtra("value", fatsValueText.text.toString())
                        putExtra("bean", calendarStatusData)

                    }
                    when (result.resultCode) {
                        RESULT_OK -> {
                            val value = result.data?.getStringExtra("result_key").toString()
                            fatsValueText.text = value

                            collectFoodInfoData?.apply {
                                fats = value.toDouble()
                            }
                        }
                    }
                }
            }
            reduceText.setOnClickListener {
                handleDecrement()
            }
            addText.setOnClickListener {
                handleIncrement()
            }
            shareLayout.setOnClickListener {

                var imgFile: File?
                val bitmap = getScreenBitmap(binding.contentLayout)
                lifecycleScope.launch {
                    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
                        val isPermissions =
                            this@FoodDtailsAc.checkPermissions(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        if (isPermissions) {
                            imgFile = saveBitmapToFile(bitmap, this@FoodDtailsAc)
                            "imgFile  $imgFile".d()
                            imgFile?.let {
                                shareFile(this@FoodDtailsAc, it)
                            }
                        }
                    } else {
                        imgFile = saveBitmapToFile(bitmap, this@FoodDtailsAc)

                        val mediaId = getImageMediaId(this@FoodDtailsAc)
                        "imgFile  $imgFile  mediaId $mediaId".d()
                        imgFile?.let {
                            mediaId?.let { k ->
                                shareMedia(this@FoodDtailsAc, k)
                            }
                        }
                    }
                }


            }
            seetingImg.setOnClickListener {
                deleteFoodText.isVisible = !deleteFoodText.isVisible
            }
            fixText.setThrottleListener {
                goToAc(FixResultAc::class.java) {
                    putExtra("foodBean", collectFoodInfoData)
                    putExtra("type", "saveFood")
                }
            }
            deleteFoodText.setOnClickListener {
                collectFoodInfoData?.let {
                    deleteList(
                        DOC_SAVE_FOOD_COLLECT_DATA,
                        DOC_SAVE_FOOD_COLLECT_DATA,
                        it.timeMillisecond
                    )
                }
                finish()
            }
            saveFoodImg.setOnClickListener {
                collectFoodInfoData?.let {
                    deleteList(
                        DOC_SAVE_FOOD_COLLECT_DATA,
                        DOC_SAVE_FOOD_COLLECT_DATA,
                        it.timeMillisecond
                    )
                }
                finish()
            }
            doneText.setOnClickListener {
                saveCollect()
                finish()
            }

        }

    }


    // 处理减号逻辑
    private fun handleDecrement() {
        if (foodType == 1) {
            if (isApproximately(currentValue, 1.0)) {
                currentValue = 0.5 // 1 → 1/2
            } else if (isApproximately(currentValue, 0.5)) {
                currentValue = 1.0 / 3 // 1/2 → 1/3
            } else if (isApproximately(currentValue, 1.0 / 3)) {
                currentValue = 0.25 // 1/3 → 1/4
            } else if (currentValue > 1.0) {
                currentValue -= 0.5 // 大于1时每次减0.5
            }
        } else {
            if (currentValue <= 1) return
            currentValue -= 1 // 大于1时每次减0.5
        }

        updateDisplay()
    }

    // 处理加号逻辑
    private fun handleIncrement() {
        if (foodType == 1) {
            if (isApproximately(currentValue, 0.25)) {
                currentValue = 1.0 / 3 // 1/4 → 1/3
            } else if (isApproximately(currentValue, 1.0 / 3)) {
                currentValue = 0.5 // 1/3 → 1/2
            } else if (isApproximately(currentValue, 0.5)) {
                currentValue = 1.0 // 1/2 → 1
            } else if (currentValue >= 1.0) {
                currentValue += 0.5 // 大于等于1时每次加0.5
            }
        } else {
            currentValue += 1 // 大于等于1时每次加0.5
        }
        updateDisplay()
    }

    // 更新显示内容
    private fun updateDisplay() {
        kotlin.runCatching {
            val displayText = if (isApproximately(currentValue, 1.0)) {
                "1"
            } else if (isApproximately(currentValue, 0.5)) {
                "1/2"
            } else if (isApproximately(currentValue, 1.0 / 3)) {
                "1/3"
            } else if (isApproximately(currentValue, 0.25)) {
                "1/4"
            } else {
//                if (currentValue < 100) {
//                    // 处理整数或小数显示
//                    if (isInteger(currentValue.toFloat())) {
//                        currentValue.roundToInt().toString()
//                    } else {
//                        String.format("%.1f", currentValue)
//                    }
//                } else {
//                    "100"
//                }
                // 处理整数或小数显示
                if (isInteger(currentValue.toFloat())) {
                    currentValue.roundToInt().toString()
                } else {
                    String.format("%.1f", currentValue)
                }
            }
            runCatching {
                val displayNum = when (displayText) {
                    "1/2" -> {
                        0.5
                    }

                    "1/3" -> {
                        0.33
                    }

                    "1/4" -> {
                        0.25
                    }

                    else -> {
                        displayText.toDouble()
                    }
                }
                when (foodType) {
                    Type1 -> {
                        collectFoodInfoData?.apply {
                            servings = displayNum
                        }
                        collectFoodInfoData?.let {
                            binding.caloriesValueText.text =
                                "${(it.calories * it.servings).toInt()}"
                            binding.carbsValueText.text = "${(it.carbs * it.servings).toInt()}"
                            binding.proteinValueText.text = "${(it.protein * it.servings).toInt()}"
                            binding.fatsValueText.text = "${(it.fats * it.servings).toInt()}"
                        }
                    }

                    Type2 -> {
                        val ing = collectFoodInfoData?.toInfoIngredients()
                        ing?.let {
                            val percent =
                                displayNum / (ing.servingTypes.first().metricAmount.toDouble()
                                    ?: 1.0)
                            collectFoodInfoData?.let {
                                binding.caloriesValueText.text =
                                    "${(it.calories * percent).toInt()}"
                                binding.carbsValueText.text = "${(it.carbs * percent).toInt()}"
                                binding.proteinValueText.text = "${(it.protein * percent).toInt()}"
                                binding.fatsValueText.text = "${(it.fats * percent).toInt()}"
                            }
                        }
                    }

                    else -> {

                    }
                }
            }
            if (foodType == 2) {
                binding.valueText.text = "${displayText}g"
            } else {
                binding.valueText.text = displayText

            }
        }
    }


    private fun isInteger(num: Float): Boolean {
        // 检查是否为NaN或无穷大
        if (java.lang.Float.isNaN(num) || java.lang.Float.isInfinite(num)) {
            return false
        }
        // 计算浮点数的向下取整值
        val floor = floor(num.toDouble()).toFloat()
        // 计算差值
        val difference = num - floor

        // 判断差值是否接近0（考虑精度问题）
        return abs(difference.toDouble()) < 1e-6
    }

    // 浮点数近似比较工具方法
    private fun isApproximately(a: Double, b: Double): Boolean {
        return abs(a - b) < EPSILON
    }

    private fun saveCollect() {
        //type=4 才需要
        if (collectFoodInfoData?.type == 4) {
            val ing = collectFoodInfoData?.toInfoIngredients()
            collectFoodInfoData?.servings =
                currentValue / (ing?.servingTypes?.first()?.metricAmount?.toDouble() ?: 1.0)
            collectFoodInfoData?.updateFoodInfoBean()
        }
        collectFoodInfoData?.let {
            CloudStore.addToList(
                DOC_SAVE_FOOD_COLLECT_DATA,
                date = DOC_SAVE_FOOD_COLLECT_DATA,
                key = it.timeMillisecond,
                data = it
            )
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: String) {
        "onMessageEvent $event".d()
        if (event == "finishFoodDetail") {
            finish()
        }

    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }


}